<?php
namespace AuctionCore\FoursStore;

/**
 * 车源列表
 * @author luchao
 */
class TransactionList  {
    /**
     * 获取车源列表 
     */
    public function getList($page = 1, $size = 10, $parame,$auth_map) {
        $user_m = new AccountManage();
        //这个地方把拼接条件拆分两个，在下面merge
        $map1 = $this->getParams($parame);
        $map2 = $this->getParams1($parame['status']);

        $map['c.suggest_max_price'] = array('gt','0');
        $map['c.suggest_min_price'] = array('gt','0');
        $new_map = array_merge($map1,$map2,$map,$auth_map);
        $t_map = array_merge($map1,$map,$auth_map);
        $cols = "c.car_id,c.car_no,c.brand_id,c.series_id,c.model_id,c.car_status,c.reserve_price,c.suggest_min_price,c.suggest_max_price
                ,c.composite_state,c.accident_level,c.re_auction_type,c.re_auction_reason,c.plate_prefix,c.plate_suffix,c.success_price,o.order_id,o.order_no,o.status as ostatus,o.remark_reject,co.owner_id,o.bidding_start_time,c.pointer_mileage,co.status,co.checker_id,co.comefrom,c.posttime";
        //全部订单数量
        $total['all_total'] = $this->count(1,$t_map);
        //待确定数量
        $total['wait_total'] = $this->count(2,$t_map);
        //交易中数量
        $total['ing_total'] = $this->count(3,$t_map);
        //交易成功数量
        $total['succ_total'] = $this->count(4,$t_map);
        //交易失败数量
        $total['failure_total'] = $this->count(5,$t_map); 
       //子查询语句
        $subQuery = M('cars')->alias('c')
                              ->field($cols)
                              ->join("LEFT JOIN ". C('DB_PREFIX') . "order o ON c.car_id=o.car_id")
                              ->join(C('DB_PREFIX')."car_owner as co ON co.owner_id=c.owner_id")
                              ->where($new_map)->order('order_id desc')
                              ->buildSql();
        $list = M()->table($subQuery.' a')->limit($size)->page($page)->group('car_id')->order('posttime desc')->select(); 
        // echo M()->getLastSql();
        $cm = new \AuctionCore\CarResource\CarModel();
        //数据处理
        foreach ($list as $key => $val) {
            $list[$key] = $val;
            $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
            $series = $cm->get_model_by_id($val['series_id'], 'series');
            $model = $cm->get_model_by_id($val['model_id']);
            $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
            $list[$key]['reserve_price'] = format_money($val['reserve_price']);
            $list[$key]['suggest_min_price'] = format_money($val['suggest_min_price']);
            $list[$key]['suggest_max_price'] = format_money($val['suggest_max_price']);
            $list[$key]['car_plate_number'] = C('PLATE_PREFIX.' . $val['plate_prefix']) . $val['plate_suffix'];
            //左前图片
            $list[$key]['left_front45'] = $this->getPics($val['car_id']);
            $in_map = array(7,8,801,9,10,11);
            if($val['car_status'] == '8'  || $val['car_status'] == '2' || $val['car_status'] == '9'){
                // $list[$key]['car_status_cn'] = '交易失败';
                $list[$key]['car_status_cn'] = C('CAR_STATUS.' . $val['car_status']);//交易成功或失败
            } elseif($val['ostatus'] == '5'){
                $list[$key]['car_status_cn'] = C('ORDER_STATUS.' . $val['ostatus']);//待确认
            } elseif(in_array($val['ostatus'], $in_map)){
                $list[$key]['car_status_cn'] = '交易中';
            } elseif(in_array($val['ostatus'], array(1,2))){
                $list[$key]['car_status_cn'] = '待上拍';
            } elseif($val['ostatus'] == 3 || $val['ostatus'] == 301 || $val['ostatus'] == 4){
                $list[$key]['car_status_cn'] = '拍卖中';
            }
            //卖家信息
            $list[$key]['buger_info'] = $user_m->carToFours($val['comefrom']);
        }
        //页数
        switch ($parame['status']) {
          case '1':
            $pages = ceil($total['all_total']/$size);
            $result = array(
                'list' => $list,
                'total' => $total['all_total'],
                'pages' => $pages,
                'all_total' =>$total
            );
            break;
          case '2':
            $pages = ceil($total['wait_total']/$size);
            $result = array(
                'list' => $list,
                'total' => $total['wait_total'],
                'pages' => $pages,
                'all_total' =>$total
            );
            break;
          case '3':
            $pages = ceil($total['ing_total']/$size);
            $result = array(
                'list' => $list,
                'total' => $total['ing_total'],
                'pages' => $pages,
                'all_total' =>$total
            );
            break;
          case '4':
            $pages = ceil($total['succ_total']/$size);
            $result = array(
                'list' => $list,
                'total' => $total['succ_total'],
                'pages' => $pages,
                'all_total' =>$total
            );
            break;
          case '5':
            $pages = ceil($total['failure_total']/$size);
            $result = array(
                'list' => $list,
                'total' => $total['failure_total'],
                'pages' => $pages,
                'all_total' =>$total
            );
            break;
          default:
            break;
        }
        
        return $result;
    }
    /**
    * @param int $car_id 根据车源id 获取车源对应前45照片
    * @return string 图片url地址
    **/
    public function getPics($car_id){
        $map['car_id'] = $car_id;
        $map['pic_key'] = array('eq','p_left_front45'); 
        $pics = M('car_pictures')->where($map)->find();
        return $pics['pic_url'];
    }

     /**
     * 车辆对应来源-获取来源名称
     */
    public function getComeName($from_id){
        $map['from_id'] = array('eq',$from_id);
        $result = M('come_from')->where($map)->find();
        return $result['from_name'];
    }

    /**
    * 获得品牌、车系、车型信息
    * @param int $id id
    * @param string $type 类型(mbrand,brand,series,model)
    * @return array
    */
    public function get_brand_by_name($name,$type='brand'){
            $condition['name'] = array('like','%'.$name.'%');
            return M('car_'.$type)->field('brand_id')->where($condition)->getField('brand_id',true);
    }   
    /**
    *@param $status 根据传过来status获取不同条件
    *@param $m 查询条件拼接的条件
    *@return int 数量
    **/
    public function count($status,$m){
      switch ($status) {
            //全部订单
           case '1':
                $where['c.car_status'] = array('in', array('2','9','8'));
                $where['o.status'] = array('in', array('5','7','8','801','9','10','11'));
                $where['_logic'] = 'OR';
                $map['_complex'] = $where;
                break;
            //待确认
            case '2':
                $map['o.status'] = array('eq', 5);
                break;
            //交易中
            case '3':
                $map['o.status'] = array('in', array('7','8','801','9','10','11'));
                break;
            //交易成功
            case '4':
                $map['c.car_status'] = array('eq', 9);
                // $map['o.status'] = array('eq',13);
                break;
            //交易失败
            case '5':
                $map['c.car_status'] = array('in',array('2','8'));
                break;
            default:
                break;
      }
      $cols = "c.car_id";
      $new_map = array_merge($map,$m);
      $buildSql =  M('cars')->alias('c')
                ->field($cols)
                ->join( "LEFT JOIN ". C('DB_PREFIX') . "order o ON c.car_id=o.car_id")
                ->join(C('DB_PREFIX')."car_owner as co ON co.owner_id=c.owner_id")
                ->where($new_map)->order('order_id desc')
                ->buildSql();
      $buildSql1 = M()->table($buildSql.' a')->group('car_id')->buildSql();
      // echo M()->getlastSql();
      $total = M()->table($buildSql1.' b')->count();
      return $total;
    }

    /**
    *拼接查询条件
    **/
    public function getParams($parame){
        $map = array();
         //car：车辆状态(0待上传协议,1 待审核,2 审核失败,3 审核驳回,4 待拍卖,5 拍卖中,6 流拍,7 待重拍, 8 交易失败, 9 交易成功)
        //order：拍单状态(1审核中,2审核驳回,3投标中,301等待竞标,4竟标中,5成效待确认,6拍单流拍,7待签约,8待付首款，
        //801已付首款,9待过户,10过户中,11待付尾款,12拍单失败,13拍单成功
        //车辆名称、车牌号、卖家信息 搜索
        if(!empty($parame['name'])){
            //车辆名称查询
            $b_result = $this->get_brand_by_name($parame['name']);
            if(empty($b_result)){
                $map['c.brand_id'] = array('eq',0);
            }else{

                $map['c.brand_id'] = array('in',$b_result);
            }
        } 
        if(!empty($parame['car_no'])){
            //车牌号查询
            $first_code = mb_substr($parame['car_no'], 0,1,'utf-8');
            $last_code = mb_substr($parame['car_no'], 1,6,'utf-8');
            $plate_num = array_flip(C('PLATE_PREFIX'));
            $map['c.plate_prefix'] = array('eq',$plate_num[$first_code]);
            $map['c.plate_suffix'] = array('eq',$last_code);
        } 
        if(!empty($parame['order_no'])){
            //拍单号查询
            $map['o.order_no'] = array('eq',$parame['order_no']);
        }
        //车辆检测时间
        if(!empty($parame['start_time']) || !empty($parame['end_time'])){
            if (empty($parame['start_time'])) {
                $map['c.posttime'] = array("elt", $parame['end_time'].' 23:59:59');
            } elseif (empty($parame['end_time'])) {
                $map['c.posttime'] = array("egt", $parame['start_time'] .' 00:00:00');
            } else {
                $map['c.posttime'] = array(array("egt", $parame['start_time'] .' 00:00:00'), array("elt", $parame['end_time'] .' 23:59:59'));
            }
        }
        return $map;
    }


    public function getParams1($status){
      $map = array();
      switch ($status) {
            //全部订单
            case '1':
                $where['c.car_status'] = array('in', array('2','9','8'));
                $where['o.status'] = array('in', array('5','7','8','801','9','10','11'));
                $where['_logic'] = 'OR';
                $map['_complex'] = $where;
                break;
            //待确认
            case '2':
                $map['o.status'] = array('eq', 5);
                break;
            //交易中
            case '3':
                $map['o.status'] = array('in', array('7','8','801','9','10','11'));
                break;
            //交易成功
            case '4':
                $map['c.car_status'] = array('eq', 9);
                // $map['o.status'] = array('eq',13);
                break;
            //交易失败
            case '5':
                $map['c.car_status'] = array('in',array('2','8'));
                break;
            default:
                break;
        }
        return $map;
    }
}